package com.snail.snailvr.views.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.model.VideoInfo;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.Util;
import com.snail.snailvr.widget.FlexibleDividerDecoration;
import com.snail.snailvr.widget.HorizontalDividerItemDecoration;
import com.snail.snailvr.widget.ThumbView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 下载列表
 * Created by snail on 16/4/13.
 */
public class DownloadListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements FlexibleDividerDecoration.PaintProvider,
        FlexibleDividerDecoration.VisibilityProvider,
        HorizontalDividerItemDecoration.MarginProvider, View.OnClickListener {
    private static final int VIEW_TYPE_HEADER = 0, VIEW_TYPE_NORMAL = 1;
    private static final int HEADER_COUNT = 1;
    private List<VideoInfo> mVideoInfoList;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private View.OnClickListener mOnClickListener;
    private View.OnLongClickListener mOnLongClickListener;
    private int dividerLeftMargin;
    private Paint dividerPaint;
    private View headerView;
    private String unknown_sources;
    private int color_normal, color_error;

    public DownloadListAdapter(Context context, List<VideoInfo> videoInfos, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
        mContext = context;
        mVideoInfoList = videoInfos;
        mLayoutInflater = LayoutInflater.from(context);
        this.mOnClickListener = clickListener;
        mOnLongClickListener = longClickListener;
        dividerLeftMargin = context.getResources().getDimensionPixelSize(R.dimen.download_list_item_divider_margin_left);
        unknown_sources = context.getString(R.string.unknown_sources);
        color_normal = context.getResources().getColor(R.color.download_title_color);
        color_error = context.getResources().getColor(R.color.invalid_live_url_color);
        dividerPaint = Util.getDividerPaint();
    }

    @Override
    public int getItemCount() {
        if (mVideoInfoList != null)
            return mVideoInfoList.size() + HEADER_COUNT;
        return HEADER_COUNT;
    }

    public VideoInfo getItem(int position) {
        position -= HEADER_COUNT;
        if (mVideoInfoList != null && position < mVideoInfoList.size())
            return mVideoInfoList.get(position);
        return null;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_HEADER:
                headerView = mLayoutInflater.inflate(R.layout.home_layout_header, parent, false);
                return new HeaderHolder(headerView);
            default:
                return new DownloadViewHolder(mLayoutInflater.inflate(R.layout.download_list_item, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof DownloadViewHolder) {
            DownloadViewHolder holder = (DownloadViewHolder) viewHolder;
            VideoInfo video = getItem(position);
            if (video != null) {
                holder.itemView.setTag(video);

                updateUi(holder, video);

                updateVideoTag(holder, video);

                holder.updateDownloadState(video.getDownloadState(),video);

            }
        }
    }

    /**
     * 根据视频信息跟新下载列表界面
     *
     * @param holder
     * @param video
     */
    private void updateUi(DownloadViewHolder holder, VideoInfo video) {
        holder.mTitle.setText(video.getVideoName());
        holder.mTitle.setTextColor(color_normal);
        holder.mTotalSize.setText(video.getStringVideoSize());
//        boolean indeterminate = status == DownloadManager.STATUS_PENDING;
//        if (!indeterminate) {
            holder.mProgressBar.setProgress(video.getDownloadedPercent());
//        }
        String path = video.getVideoPath();
        holder.mThumbView.setImageUrlAndReUse(path);//TODO 是否是在下載完成之後獲取
    }

    /**
     * 更新视频缩略图左上角的tag标签
     *
     * @param holder
     * @param video
     */
    private void updateVideoTag(DownloadViewHolder holder, VideoInfo video) {
        if (video.isDemoVideo()) {
            holder.mVideoTag.setVisibility(View.VISIBLE);
            holder.mVideoTag.setImageResource(R.drawable.ic_tag_demo);
        } else if (video.isNewVideo()) {
            holder.mVideoTag.setVisibility(View.VISIBLE);
            holder.mVideoTag.setImageResource(R.drawable.ic_tag_new);
        } else {
            holder.mVideoTag.setVisibility(View.GONE);
        }
    }

//    private void setDownloadTag(DownloadViewHolder holder, VideoInfo video, int status) {
//        holder.mDownloadStatus.setOnClickListener(this);
//        holder.mDownloadStatus.setTag(R.id.download_id, video.getVideoId());
//        holder.mDownloadStatus.setTag(R.id.download_status_icon, status);
//    }

//    private void switchViewToResume(DownloadViewHolder holder, VideoInfo video) {
//        holder.mDownloadSpeed.setVisibility(View.VISIBLE);
//        holder.mDownloadSpeed.setText(video.getDownloadSpeedAndPercent());
//        holder.mDownloadStatus.setImageResource(R.drawable.ic_pause);
//    }
//
//    private void switchViewToPause(DownloadViewHolder holder, VideoInfo video, int status) {
//        holder.mDownloadSpeed.setVisibility(View.VISIBLE);
//        holder.mDownloadSpeed.setText(getStatusStringId(status, video.getReason()));
//        holder.mDownloadStatus.setImageResource(R.drawable.ic_resume);
//    }
//
//    private void switchViewToWait(DownloadViewHolder holder, VideoInfo video, int status) {
//        holder.mDownloadSpeed.setVisibility(View.VISIBLE);
//        holder.mDownloadSpeed.setText(getStatusStringId(status, video.getReason()));
//        holder.mDownloadStatus.setImageResource(R.drawable.ic_download_wait);
//    }
//
//    private void downloadFailed(DownloadViewHolder holder, VideoInfo videoInfo, int status) {
//        //下载失败
//        if (videoInfo.getDownloadedSize() <= 0) {
//            holder.mTitle.setTextColor(color_error);
//            holder.mTitle.setText(unknown_sources);
//            holder.mTotalSize.setVisibility(View.GONE);
//            holder.mDownloadSpeed.setVisibility(View.GONE);
//            holder.mDownloadStatus.setVisibility(View.GONE);
//        } else {
//            setDownloadTag(holder, videoInfo, status);
//            holder.mDownloadStatus.setImageResource(R.drawable.ic_retry_download);
//        }
//    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0)
            return VIEW_TYPE_HEADER;
        return VIEW_TYPE_NORMAL;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }


    private int getStatusStringId(int status, int reason) {
        switch (status) {
            case DownloadManager.STATUS_FAILED:
                return R.string.download_error;

            case DownloadManager.STATUS_SUCCESSFUL:
                return R.string.download_success;

            case DownloadManager.STATUS_PENDING:
            case DownloadManager.STATUS_RUNNING:
                return R.string.download_running;

            case DownloadManager.STATUS_PAUSED:
                if (reason == DownloadManager.PAUSED_QUEUED_FOR_WIFI) {
                    return R.string.download_queued;
                } else {
                    return R.string.download_paused;
                }
            default:
                LogUtils.e("Unknown status: " + status);
                return R.string.unknow_status;

        }
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.download_status_icon:
                if ((int) v.getTag(R.id.download_status_icon) == DownloadManager.STATUS_PAUSED) {
                    if(DialogUtils.showJudgeNetDialog(null,new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadHelper.getDownloadManager().resumeDownload((long) v.getTag(R.id.download_id));
                        }
                    }))
                        return;
                    DownloadHelper.getDownloadManager().resumeDownload((long) v.getTag(R.id.download_id));
//                    ((ImageView)v).setImageResource(R.drawable.ic_download_wait);
                } else if ((int) v.getTag(R.id.download_status_icon) == DownloadManager.STATUS_RUNNING) {
                    DownloadHelper.getDownloadManager().pauseDownload((long) v.getTag(R.id.download_id));
//                    ((ImageView)v).setImageResource(R.drawable.ic_download_wait);
                } else if ((int) v.getTag(R.id.download_status_icon) == DownloadManager.STATUS_FAILED) {
                    if(DialogUtils.showJudgeNetDialog(null,new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadHelper.getDownloadManager().restartDownload((long) v.getTag(R.id.download_id));
                        }
                    }))
                        return;
                    DownloadHelper.getDownloadManager().restartDownload((long) v.getTag(R.id.download_id));
                }
                break;
        }
    }

    @Override
    public int dividerLeftMargin(int position, RecyclerView parent) {
        return dividerLeftMargin;
    }

    @Override
    public int dividerRightMargin(int position, RecyclerView parent) {
        return 0;
    }

    @Override
    public Paint dividerPaint(int position, RecyclerView parent) {
        return dividerPaint;
    }

    @Override
    public boolean shouldHideDivider(int position, RecyclerView parent) {
        return false;
    }

    class DownloadViewHolder extends BaseDownloadViewHolder{
        @Bind(R.id.video_thumb)
        ThumbView mThumbView;
        @Bind(R.id.download_title)
        TextView mTitle;
        @Bind(R.id.total_size)
        TextView mTotalSize;
        @Bind(R.id.download_speed)
        TextView mDownloadSpeed;
        @Bind(R.id.download_progress)
        ProgressBar mProgressBar;

        @Bind(R.id.video_duration)
        TextView mDuration;
        @Bind(R.id.video_tag)
        ImageView mVideoTag;
        View itemView;

        public DownloadViewHolder(View itemView) {
            super(mContext,itemView);
            this.itemView = itemView;
            itemView.setOnClickListener(mOnClickListener);
            itemView.setOnLongClickListener(mOnLongClickListener);
            mThumbView.setImagePlaceHolder(R.drawable.ic_downloading_holder);
        }


        @Override
        void onSuccess(VideoInfo videoInfo) {
            //下载完成
            mTotalSize.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.GONE);
            mDuration.setVisibility(View.VISIBLE);
            mDownloadStatus.setVisibility(View.GONE);
            mDuration.setText(videoInfo.getFormatDuration());
            mDownloadSpeed.setVisibility(View.GONE);
        }

        @Override
        void onPause(VideoInfo video) {
            pauseOrRunning();
            mDownloadSpeed.setVisibility(View.VISIBLE);
            mDownloadSpeed.setText(getStatusStringId(DownloadManager.STATUS_PAUSED, video.getReason()));
            mDownloadStatus.setImageResource(R.drawable.ic_pause);
        }

        @Override
        void onRunning(VideoInfo videoInfo) {
            pauseOrRunning();
            mDownloadSpeed.setVisibility(View.VISIBLE);
            mDownloadSpeed.setText(videoInfo.getDownloadSpeedAndPercent());
            mDownloadStatus.setImageResource(R.drawable.ic_resume);
        }

        private void pauseOrRunning() {
            //正在下载或者暂停下载
            mTotalSize.setVisibility(View.VISIBLE);
            mDownloadStatus.setVisibility(View.VISIBLE);
            mDuration.setVisibility(View.GONE);
            mProgressBar.setVisibility(View.VISIBLE);

        }

        @Override
        void onWait(VideoInfo videoInfo) {
            pauseOrRunning();
            mDownloadSpeed.setVisibility(View.VISIBLE);
            mDownloadSpeed.setText(getStatusStringId(DownloadManager.STATUS_PENDING, videoInfo.getReason()));
            mDownloadStatus.setImageResource(R.drawable.ic_download_wait);
        }

        @Override
        void onFail(VideoInfo videoInfo) {
            //下载失败
            if (videoInfo.getDownloadedSize() <= 0) {
                mTitle.setTextColor(color_error);
                mTitle.setText(unknown_sources);
                mTotalSize.setVisibility(View.GONE);
                mDownloadSpeed.setVisibility(View.GONE);
                mDownloadStatus.setVisibility(View.GONE);
            } else {
                mDownloadStatus.setImageResource(R.drawable.ic_retry_download);
            }
        }

        @Override
        void onInit(VideoInfo videoInfo) {

        }

        @Override
        void switchDownloadState(VideoInfo videoInfo,int viewId) {
            if(viewId==R.id.download_status_icon) {
                switch (videoInfo.getDownloadState()) {
                    case DownloadManager.STATUS_PAUSED:
                        mDownloadStatus.setImageResource(R.drawable.ic_resume);
                        videoInfo.setDownloadState(DownloadManager.STATUS_RUNNING);
                        break;
                    case DownloadManager.STATUS_RUNNING:
                        mDownloadStatus.setImageResource(R.drawable.ic_pause);
                        videoInfo.setDownloadState(DownloadManager.STATUS_PAUSED);
                        break;
                }
                notifyDataSetChanged();
            }
        }


    }

    class HeaderHolder extends RecyclerView.ViewHolder {

        public HeaderHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IntentUtils.startAllVideoListActivity(mContext);
                }
            });
        }
    }

    public int getHeaderCount() {
        return HEADER_COUNT;
    }

    public View getHeaderView() {
        return headerView;
    }
}
